import 'dart:io';
import 'package:flutter/material.dart';
import 'package:file_picker/file_picker.dart';
import 'asr_ffi.dart';

/// 测试日志功能的示例页面
class TestLoggingPage extends StatefulWidget {
  const TestLoggingPage({super.key});

  @override
  State<TestLoggingPage> createState() => _TestLoggingPageState();
}

class _TestLoggingPageState extends State<TestLoggingPage> {
  String _logFilePath = '未创建';
  String _recognitionResult = '';
  bool _isRecognizing = false;
  String _selectedAudioFile = '';

  @override
  void initState() {
    super.initState();
    _initializeAsrAndLogging();
  }

  /// 初始化ASR和日志系统
  Future<void> _initializeAsrAndLogging() async {
    try {
      await AsrFFI.initialize();
      final logPath = AsrFFI.getLogFilePath();
      setState(() {
        _logFilePath = logPath ?? '创建失败';
      });

      // 显示日志文件路径
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('日志文件已创建: $logPath'),
            duration: const Duration(seconds: 3),
          ),
        );
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('初始化失败: $e'), backgroundColor: Colors.red),
        );
      }
    }
  }

  /// 选择音频文件
  Future<void> _selectAudioFile() async {
    try {
      FilePickerResult? result = await FilePicker.platform.pickFiles(
        type: FileType.custom,
        allowedExtensions: ['wav', 'mp3', 'flac', 'm4a', 'aac', 'ogg'],
      );

      if (result != null && result.files.single.path != null) {
        setState(() {
          _selectedAudioFile = result.files.single.path!;
        });

        // 检查文件信息
        final fileInfo = AsrFFI.getAudioFileInfo(_selectedAudioFile);

        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text(
                '已选择文件: ${fileInfo['name']}\n'
                '大小: ${fileInfo['sizeString']}\n'
                '支持: ${fileInfo['isSupported'] ? '是' : '否'}',
              ),
            ),
          );
        }
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('选择文件失败: $e'), backgroundColor: Colors.red),
        );
      }
    }
  }

  /// 执行语音识别
  Future<void> _performRecognition() async {
    if (_selectedAudioFile.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('请先选择音频文件'),
          backgroundColor: Colors.orange,
        ),
      );
      return;
    }

    setState(() {
      _isRecognizing = true;
      _recognitionResult = '识别中...';
    });

    try {
      // 执行离线识别（这里会产生详细的日志）
      final result = await AsrFFI.performOfflineRecognition(_selectedAudioFile);

      setState(() {
        _recognitionResult = result;
        _isRecognizing = false;
      });

      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('识别完成: $result'),
            backgroundColor: Colors.green,
          ),
        );
      }
    } catch (e) {
      setState(() {
        _recognitionResult = '识别失败: $e';
        _isRecognizing = false;
      });

      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('识别失败: $e'), backgroundColor: Colors.red),
        );
      }
    }
  }

  /// 查看日志文件内容
  Future<void> _viewLogContent() async {
    try {
      final content = await AsrFFI.getLogFileContent();

      if (mounted) {
        showDialog(
          context: context,
          builder: (context) => AlertDialog(
            title: const Text('日志文件内容'),
            content: SizedBox(
              width: double.maxFinite,
              height: 400,
              child: SingleChildScrollView(
                child: Text(
                  content,
                  style: const TextStyle(fontFamily: 'monospace', fontSize: 12),
                ),
              ),
            ),
            actions: [
              TextButton(
                onPressed: () => Navigator.of(context).pop(),
                child: const Text('关闭'),
              ),
            ],
          ),
        );
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('读取日志失败: $e'), backgroundColor: Colors.red),
        );
      }
    }
  }

  /// 打开日志文件夹
  Future<void> _openLogFolder() async {
    try {
      await AsrFFI.openLogFileFolder();

      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('已打开日志文件夹'),
            backgroundColor: Colors.green,
          ),
        );
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('打开文件夹失败: $e'), backgroundColor: Colors.red),
        );
      }
    }
  }

  /// 清空日志并删除文件
  Future<void> _clearLogs() async {
    try {
      final deleted = await AsrFFI.deleteLogFile();

      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(deleted ? '日志文件已删除' : '日志文件不存在'),
            backgroundColor: deleted ? Colors.green : Colors.orange,
          ),
        );
      }

      if (deleted) {
        setState(() {
          _logFilePath = '已删除';
        });
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('删除日志失败: $e'), backgroundColor: Colors.red),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('ASR 日志测试'),
        backgroundColor: Colors.blue,
        foregroundColor: Colors.white,
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            // 日志文件信息
            Card(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text(
                      '日志文件信息',
                      style: TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const SizedBox(height: 8),
                    Text('路径: $_logFilePath'),
                    const SizedBox(height: 8),
                    Row(
                      children: [
                        Expanded(
                          child: ElevatedButton(
                            onPressed: _viewLogContent,
                            child: const Text('查看日志内容'),
                          ),
                        ),
                        const SizedBox(width: 8),
                        Expanded(
                          child: ElevatedButton(
                            onPressed: _openLogFolder,
                            child: const Text('打开文件夹'),
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 8),
                    ElevatedButton(
                      onPressed: _clearLogs,
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.red,
                      ),
                      child: const Text(
                        '删除日志文件',
                        style: TextStyle(color: Colors.white),
                      ),
                    ),
                  ],
                ),
              ),
            ),

            const SizedBox(height: 16),

            // 音频文件选择
            Card(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text(
                      '音频文件选择',
                      style: TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const SizedBox(height: 8),
                    Text(
                      '已选择: ${_selectedAudioFile.isEmpty ? '无' : _selectedAudioFile.split(Platform.pathSeparator).last}',
                    ),
                    const SizedBox(height: 8),
                    ElevatedButton(
                      onPressed: _selectAudioFile,
                      child: const Text('选择音频文件'),
                    ),
                  ],
                ),
              ),
            ),

            const SizedBox(height: 16),

            // 语音识别
            Card(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text(
                      '语音识别测试',
                      style: TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const SizedBox(height: 8),
                    ElevatedButton(
                      onPressed: _isRecognizing ? null : _performRecognition,
                      child: _isRecognizing
                          ? const Row(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                SizedBox(
                                  width: 16,
                                  height: 16,
                                  child: CircularProgressIndicator(
                                    strokeWidth: 2,
                                  ),
                                ),
                                SizedBox(width: 8),
                                Text('识别中...'),
                              ],
                            )
                          : const Text('开始识别'),
                    ),
                    const SizedBox(height: 16),
                    const Text(
                      '识别结果:',
                      style: TextStyle(fontWeight: FontWeight.bold),
                    ),
                    const SizedBox(height: 8),
                    Container(
                      width: double.infinity,
                      padding: const EdgeInsets.all(12),
                      decoration: BoxDecoration(
                        border: Border.all(color: Colors.grey),
                        borderRadius: BorderRadius.circular(4),
                      ),
                      child: Text(
                        _recognitionResult.isEmpty
                            ? '暂无结果'
                            : _recognitionResult,
                        style: const TextStyle(fontSize: 16),
                      ),
                    ),
                  ],
                ),
              ),
            ),

            const Spacer(),

            // 说明文字
            const Card(
              child: Padding(
                padding: EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '使用说明:',
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    SizedBox(height: 8),
                    Text('1. 应用启动时会自动在桌面创建日志文件'),
                    Text('2. 选择一个音频文件进行识别测试'),
                    Text('3. 点击"开始识别"会产生详细的日志记录'),
                    Text('4. 可以查看日志内容或打开日志文件夹'),
                    Text('5. 日志包含了识别过程的所有详细信息'),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
